/*
 * Copyright (c) 2012 Android Dev Freelancer Team. All Rights Reserved.
 */
package com.devgroupvn.dota;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

/* 
 * @class VideoDota2Activity
 * @author tkminh
 * @version 1.0, 22 May 2012
 * 
 */

public class VideoDota2Activity extends Activity
{

	/** Control Element */
	public WebView mWebView;
	public ListView mListView;
	public Button btnMore;
	public ProgressBar pb;
	AdView adView;
	TextView tv_new;
	TextView tv_vod;
	public static String[] mValText;

	// current
	public static int index = 1;
	public static String curcat = "";

//	public LayoutInflater inflater;
//	public View inflaterMore;

	public static List<Entry> listData = new LinkedList<Entry>();
	public static List<Post> listDataNEWS = new LinkedList<Post>();
	public PostAdapter adapter = new PostAdapter(this, listData);
	public NEWSAdapter adapterNEWS;// = new NEWSAdapter(this, listDataNEWS);
	public static ArrayList<Post> listpost;

	// async task
	public Async async;

	/** Web Items */
	public static WebContent mWebContent;

	Context mContext;
	private static String strLayout = "MAINAPPLICATION";
	private final static String LAYOUT_SHARE = "SHARESNS";
	private final static String LAYOUT_MAIN = "MAINAPPLICATION";
	public static boolean hasApp =false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.main);
		adView = (AdView) findViewById(R.id.adView);
		new AsyncCheckApp(this).execute();
//		setActivityDefault();
		if (isNetworkAvailable())
		{
			initiation();
			loadmore();
			loadContent();
			action();
		}
		else
		{
			NetWorkFalse();
		}
	}

	private void setActivityDefault()
	{

		setContentView(R.layout.main);
		adView = (AdView) findViewById(R.id.adView);
		if (isNetworkAvailable())
		{
			initiation();
			TabVODS();
//			loadmore();
//			loadContent();
			action();
		}
		else
		{
			NetWorkFalse();
		}
	}

	/**
	 * Init the controls element
	 */
	public static int page = 0;
	private static int pagetam = 0;
	private static String Seleted = Configs.TAB_VOD;

	private void initiation()
	{
		
		async = new Async("http://www.joindota.com/en/vods", adapter);

		mWebContent = new WebContent();

		mListView = (ListView) findViewById(R.id.listView);
		tv_new = (TextView) findViewById(R.id.tv_firstItem);
		tv_vod = (TextView) findViewById(R.id.tv_lastItem);
		tv_new.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				if (Seleted.equals(Configs.TAB_VOD))
				{
					tv_new.setText(getString(R.string.VOD));
					tv_vod.setText(getString(R.string.NEW));
					Seleted = Configs.TAB_NEW;
					loadContentNEW();
				}
				else
				{
					tv_new.setText(getString(R.string.NEW));
					tv_vod.setText(getString(R.string.VOD));
					Seleted = Configs.TAB_VOD;
					TabVODS();
				}
			}
		});

		setupAdwhirl();
	}

	private void loadmore()
	{
		mListView.setOnScrollListener(new OnScrollListener()
		{

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState)
			{

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
			{
				if (totalItemCount == 0) { return; }
				if (!isNetworkAvailable()) { return; }
				int lastitem = firstVisibleItem + visibleItemCount;
				if (Seleted.equals(Configs.TAB_VOD))
				{
					if (lastitem == totalItemCount && page > pagetam && page < 31)
					{
						pagetam = page;
						async = new Async("http://www.joindota.com/en/vods", adapter);
						async.url = "http://www.joindota.com/en/vods/&archiv_page=" + page;
						async.execute();
					}
				}
			}
		});
	}

	@Override
	protected void onPause()
	{
		//
		if (async != null && !async.isCancelled())
		{
			async.isCancelled();
		}
		super.onPause();
	}

	private void TabVODS()
	{
		if(asyncloadnew!=null && asyncloadnew.isCancelled())
		{
			asyncloadnew.cancel(true);
		}
		mListView.setAdapter(adapter);
		loadmore();
	}

	private void TabNEW()
	{

	}

	@Override
	public void onBackPressed()
	{
		if (strLayout.equals(LAYOUT_SHARE))
		{
			strLayout= LAYOUT_MAIN;
			setActivityDefault();
		}
		else if (strLayout.equals(LAYOUT_MAIN))

		{
			AlertDialog.Builder builder = new AlertDialog.Builder(VideoDota2Activity.this);
			builder.setTitle("JoinDota").setMessage(R.string.close_app).setCancelable(true)
					.setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							dialog.cancel();
						}
					}).setNegativeButton(getString(R.string.ok), new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							android.os.Process.killProcess(android.os.Process.myPid());
						}
					}).create().show();
		}
	}


	private void setupAdwhirl()
	{
		try
		{
			final Handler handle = new Handler();
			final Runnable run = new Runnable()
			{

				@Override
				public void run()
				{
					AdRequest request = new AdRequest();
					adView.loadAd(request);
					handle.postDelayed(this, 5000);

				}
			};
			handle.postDelayed(run, 5000);
		}
		catch (Exception e)
		{

		}
	}

	/**
	 * Load content from url and display
	 */
	private void loadContent()
	{
		// mListView.setDivider(getResources().getDrawable(R.color.reddota));
		
		progressDialog = ProgressDialog.show(VideoDota2Activity.this, null, "Waiting..", true, false);
		
		mListView.setAdapter(adapter);
		async.url = "http://www.joindota.com/en/vods";
		async.execute();
	}

	AsyntaskLoadNews asyncloadnew;

	private void loadContentNEW()
	{
		// mListView.setDivider(getResources().getDrawable(R.color.transparent));
		if (listDataNEWS.size() == 0)
		{
			progressDialog = ProgressDialog.show(VideoDota2Activity.this, null, "Waiting..", true, false);
		}

		mListView.setAdapter(adapterNEWS);
		asyncloadnew.execute();
	}

	public class AsyntaskLoadNews extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params)
		{
			listDataNEWS = new NewsArchive().getListNew();
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{

			adapterNEWS = new NEWSAdapter(VideoDota2Activity.this, listDataNEWS);
			mListView.setAdapter(adapterNEWS);
			if (progressDialog.isShowing())
			{
				progressDialog.dismiss();
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
		}

	}

	/**
	 * Handle action event
	 */
	private void action()
	{
		/** on item click event for list view */
		mListView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> a, View v, int position, long id)
			{
				// Intent i = new Intent(VideoDota2Activity.this,
				// ViewPost.class);
				// // i.putExtra("position", position);
				// i.putExtra("title", listData.get(position).mDescription);
				// i.putExtra("image", listData.get(position).mImage);
				// i.putExtra("link", listData.get(position).mLink);
				// startActivity(i);
				if (!isNetworkAvailable()) { return; }
				if (Seleted.equals(Configs.TAB_VOD))
				{
					// new
					// AsyncGetVideoLink(listData.get(position).mLink).execute();
//					ShareSNS shareSNS = new ShareSNS(VideoDota2Activity.this, mContext);
//					shareSNS.setLink(listData.get(position));
//					strLayout = LAYOUT_SHARE;

				}
				if (Seleted.equals(Configs.TAB_NEW))
				{
					String link = listDataNEWS.get(position).link;
					Intent intent = new Intent(VideoDota2Activity.this, WebViewNews.class);
					intent.putExtra("link", link);
					startActivity(intent);
				}

			}
		});
	}

	private boolean isNetworkAvailable()
	{

		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();
		return (info != null && info.isConnected());
	}

	public static ProgressDialog progressDialog;
	private class AsyncCheckApp extends AsyncTask<Void,Void,Void>
	{
		Context aContext;
		boolean _hasApp;
		AsyncCheckApp (Context _context)
		{
			aContext = _context;
		}
		@Override
		protected Void doInBackground(Void... params)
		{
			CheckAppInstall check = new CheckAppInstall(aContext);
			_hasApp = check.checkApp(aContext);
			return null;
		}
		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
//			Application.getInstance().putData("HASAPP", hasApp);
			hasApp=_hasApp;
		}
		
		
	}
	public class AsyncGetVideoLink extends AsyncTask<Void, Void, Void>
	{
		String link;
		String path;

		public AsyncGetVideoLink(String _link)
		{
			link = _link;
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			progressDialog = ProgressDialog.show(VideoDota2Activity.this, null, "Waiting..", true, false);
		}

		@Override
		protected Void doInBackground(Void... arg0)
		{

			try
			{
				path = new WebContent().getPostContent(link);
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			progressDialog.dismiss();
			// Intent intent = new Intent(Intent.ACTION_VIEW);
			// intent.setDataAndType(Uri.parse(path), "video/*");
			// startActivity(intent);
			CheckAppInstall check = new CheckAppInstall(mContext);
			boolean hasApp = check.checkApp(mContext);
			if (hasApp)
			{
				// Intent intent = new Intent(Intent.ACTION_VIEW);
				// PackageManager pk = getPackageManager();
				// intent =
				// pk.getLaunchIntentForPackage(check.packageNameRockPlayer);
				// intent.setDataAndType(Uri.parse(path), "video/*");
				// startActivity(intent);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.parse(path), "video/*");
				startActivity(intent);
			}
			else
			{
				check.installApp(mContext);
			}
		}
	}

	private void NetWorkFalse()
	{
		Context _context = (Context) this;
		AlertDialog.Builder askToDelete = new AlertDialog.Builder(_context);
		askToDelete.setMessage(getString(R.string.connection_error));
		askToDelete.setPositiveButton(getString(R.string.exists), new DialogInterface.OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		});
		AlertDialog dialog = askToDelete.create();
		dialog.show();
	}

}
